package com.buss.admin.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.jweb.core.bean.PageMode;
import org.jweb.core.query.hibernate.qbc.CriteriaQuery;
import org.jweb.core.util.MyBeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.buss.admin.service.IArticleDetailService;
import com.buss.admin.service.IArticleService;
import com.buss.admin.trans.form.ArticleForm;
import com.buss.article.trans.form.ArticleAllForm;
import com.buss.article.trans.vo.ArticleVO;
import com.buss.article.trans.vo.ArticledetailVO;
import com.buss.common.entity.HxActive;
import com.buss.common.entity.HxActiveDetail;
import com.buss.common.entity.HxArticle;
import com.buss.common.entity.HxArticleDetail;
import com.buss.common.model.json.EasyUIDataGridResult;
import com.buss.common.model.json.HXResult;
import com.buss.common.service.SysServiceI;
import com.buss.common.util.IDUtils;

@Controller
@RequestMapping("/admin/article")
public class AdminArticleController {
	@Autowired
	private SysServiceI sysService;
	@Autowired
	private IArticleService articleService;
	@Autowired
	private IArticleDetailService articleDetailService;

	@RequestMapping("/save")
	@ResponseBody
	public HXResult articleSave(ArticleAllForm articleAllForm, String content) {

		try {
			HxArticle article = new HxArticle();
			MyBeanUtils.copyBeanNotNull2Bean(articleAllForm, article);
			/*
			 * 插入文章数据操作
			 */
			long articleId = IDUtils.getArticleId();
			article.setId(articleId);

			// 补全日期属性值
			Date date = new Date();
			article.setUpdateTime(date);
			article.setCreateTime(date);
			article.setPublishTime(date);

			article.setStatus(1);

			System.out.println("cid=" + article.getCid());
//			this.sysService.saveOrUpdate(article);
//			this.sysService.save(article);
			String sql = "insert into hxclub.hx_article "
					+ "(create_time, editor, img_url, keywords, levelclass, publish_time, source, status, summary, title, update_time, video_url, id, cid) "
					+ "values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
			this.sysService.executeSql(sql, 
					article.getCreateTime(),
					article.getEditor(),
					article.getImgUrl(),
					article.getKeywords(),
					article.getLevelclass(),
					article.getPublishTime(),
					article.getSource(),
					article.getStatus(),
					article.getSummary(),
					article.getTitle(),
					article.getUpdateTime(),
					article.getVideoUrl(),
					article.getId(),
					article.getCid()
					);

			/*
			 * 插入文章详情操作
			 */
			HxArticleDetail articleDetail = new HxArticleDetail();
			articleDetail.setContent(content);
			articleDetail.setId(articleId);
			articleDetail.setUpdateTime(date);
			articleDetail.setCreateTime(date);
			articleDetail.setLevelclass(Integer.parseInt(articleAllForm.getLevelclass()));

			// 关联文章表数据
			articleDetail.setHxArticle(article);

			article.setArticleDetail(articleDetail);

			this.sysService.saveOrUpdate(articleDetail);

			return HXResult.ok("发布文章成功！");

		} catch (Exception e) {
			e.printStackTrace();
			return HXResult.build(500, "服务器繁忙，发布文章失败！请稍后再试！");
		}

	}
	
	
	@RequestMapping("/list")
	@ResponseBody
	public EasyUIDataGridResult getArticleList(ArticleForm articleForm) {

		// 分页查询
		CriteriaQuery cq = articleForm.getCriteriaQuery();

		int pageNo = Integer.parseInt(articleForm.getPage());
		int pageSize = Integer.parseInt(articleForm.getRows());

		// 定义返回数据格式
		EasyUIDataGridResult result = new EasyUIDataGridResult();
		PageMode pageMode = articleService.list4page(cq, pageNo, pageSize);
		
		List<HxArticle> articles = pageMode.getResult();
		
		// 封装返回数据
		List<ArticleVO> articleVOs = new ArrayList<>();
		ArticleVO articleVO = null;
		for(HxArticle ha : articles) {
			articleVO = new ArticleVO();
			articleVO.copyEntity(ha);
			
			
			articleVOs.add(articleVO);
		}
		pageMode.setResult(articleVOs);

		// 封装数据
		result.setRows(pageMode.getResult());
		result.setTotal(pageMode.getTotal());
		return result;

	}

	@RequestMapping("/delete")
	@ResponseBody
	public HXResult delete(String ids, HttpServletRequest request) {
		try {
			String[] idStrings = ids.split(",");
			for (String id : idStrings) {
				articleService.deleteEntityById(HxArticle.class, Long.parseLong(id));
				articleDetailService.deleteEntityById(HxArticleDetail.class, Long.parseLong(id));
			}

			return HXResult.ok("删除文章成功！");
		} catch (Exception e) {
			e.printStackTrace();
			return HXResult.build(500, "服务器发生错误，删除文章数据失败！");
		}
	}
	
	@RequestMapping(value="/update", method={RequestMethod.GET, RequestMethod.POST})
	@ResponseBody
	public HXResult editActive(HxArticle active, String content ) {
		try {
			Date datatime = new Date();
			active.setUpdateTime(datatime);
			HxArticleDetail detail = new HxArticleDetail();
			detail.setContent(content);
			detail.setUpdateTime(datatime);
			active.setArticleDetail(detail);
			articleService.saveOrUpdate(active);
			return HXResult.ok("修改成功");
		} catch (Exception e) {
			
			e.printStackTrace();
			return HXResult.build(500, "修改失败");
		}
	}
	
	@RequestMapping("/articleDetail")
	@ResponseBody
	public Object articleDetail(String id, HttpServletRequest request) {
		try {
			HxArticle detail = articleService.get(HxArticle.class, Long.parseLong(id));
			ArticledetailVO articledetailVO = new ArticledetailVO();
			articledetailVO.copyEntity(detail);
			return articledetailVO;
		} catch (Exception e) {
			e.printStackTrace();
			return HXResult.build(500, "服务器发生错误，文章数据失败！");
		}
	}
	
	@RequestMapping("/{path}")
	public String goPath(@PathVariable String path) {
		System.out.println("path:" + path);
		return "admin/article/" + path;
	}



}
